﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Minio;
using Minio.DataModel;
using Minio.Exceptions;
using System.Threading;
using System.Threading.Tasks;
using System.Reactive.Linq;
using Thingpower.SS.OSS.Core;
using Thingpower.SS.OSS.Models;

namespace Thingpower.SS.OSS.BackgroundPages
{
    public partial class PageResources : System.Web.UI.Page
    {
        private string _accessKey;
        private string _secretKey;
        private string _domain;
        private string _bucketName;
        private static MinioClient _client;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!OSSPlugin.Instance.AdminApi.HasSystemPermissions())
            {
                HttpContext.Current.Response.Write("<h1>未授权访问</h1>");
                HttpContext.Current.Response.End();
                return;
            }

            PluginConfigInfo _config = Utils.GetConfig();

            _accessKey = _config.KeyAccess;
            _secretKey = _config.KeySecret;
            _domain = _config.Domain;
            _bucketName = _config.Bucket;

            _client = new MinioClient($"{_domain}:80", _accessKey, _secretKey);

            RptResources.DataSource = GetResourcesItemList();
            RptResources.ItemDataBound += RptResources_ItemDataBound;
            RptResources.DataBind();
        }

        private void RptResources_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;

            var ltlIndex = (Literal)e.Item.FindControl("ltlIndex");
            var ltlKey = (Literal)e.Item.FindControl("ltlKey");
            var ltlSize = (Literal)e.Item.FindControl("ltlSize");
            var ltlLastModifiedDateTime = (Literal)e.Item.FindControl("ltlLastModifiedDateTime");
            var ltlCopyUrl = (HyperLink)e.Item.FindControl("lnkCopyUrl");

            var _model = (Item)e.Item.DataItem;

            ltlIndex.Text = (e.Item.ItemIndex + 1).ToString();
            ltlKey.Text = _model.Key;
            ltlSize.Text = GetFileSizeString(_model.Size);
            ltlLastModifiedDateTime.Text = _model.LastModifiedDateTime.ToShortDateString();
            ltlCopyUrl.ToolTip = $"http://{_domain}/{_bucketName}/{_model.Key}";

            ltlCopyUrl.Attributes.Add("onclick", "copyUrl(this)");

        }

        private List<Item> GetResourcesItemList()
        {
            try
            {
                IObservable<Item> observable = _client.ListObjectsAsync("xwsqxy");
                List<Item> _listItem = new List<Item>();
                List<string> isCompleted = new List<string>();

                IDisposable subscription = observable.ToList().Subscribe(
                    item => _listItem.AddRange(item),
                    ex => Console.WriteLine("OnError: {0}", ex),
                    () => isCompleted.Add("complete"));

                while (isCompleted.Count == 0)
                {
                    observable.Wait();
                }

                subscription.Dispose();

                return _listItem;
            }
            catch (MinioException ex)
            {
                throw ex;
            }
        }

        private string GetFileSizeString(ulong size)
        {
            string _fileSizeString;

            if (size < 1024)
            {
                _fileSizeString = $"{size}B";
            }
            else if (size < 1048576)
            {
                _fileSizeString = $"{Math.Round((double)(size / 1024), 2)}KB";
            }
            else if (size < 1073741824)
            {
                
                _fileSizeString = $"{Math.Round((double)(size / 1048576), 2)}MB"; ;
            }
            else
            {
                _fileSizeString = $"{Math.Round((double)(size / 1073741824), 2)}GB";
            }

            return _fileSizeString;
        }
        
    }
}